package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;

/**
 * @Author Stringzhua
 * @Date 2024/11/5 11:15
 * description:
 */
public class Demo03 {
    public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class clazz = Order.class;
        //获取无参构造方法
        Constructor c0 = clazz.getConstructor();
        //获取有参构造方法
        Constructor c1 = clazz.getConstructor(int.class, double.class, LocalDateTime.class);

        //调用无参构造方法
        //方式1:
        Object obj1 = clazz.newInstance();
        System.out.println(obj1);
        //方式2:
        Object obj2 = c0.newInstance();
        System.out.println(obj2);

        //调用有参构造方法
//        Order order = new Order(500, 3.14, LocalDateTime.of(2024, 11, 05, 11, 22));
        Object obj3 = c1.newInstance(500, 3.14, LocalDateTime.of(2024, 11, 05, 11, 22));
        System.out.println(obj3);

        //遍历所有的构造方法
        //获取所有public修饰的Constructor
        Constructor[] constructors = clazz.getConstructors();
        for (Constructor c : constructors) {
            System.out.println(c);
        }
    }
}

class Order {
    private int money;
    private double sale;
    private LocalDateTime time;

    public Order() {
        System.out.println("调用的是无参构造方法");
    }

    public Order(int money, double sale, LocalDateTime time) {
        System.out.println("调用的是有参构造方法");
        this.money = money;
        this.sale = sale;
        this.time = time;
    }
}
